package com.cr.crandroid.ui.person.car;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.gridlayout.widget.GridLayout;

import android.widget.ImageButton;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.navigation.Navigation;

import com.bumptech.glide.Glide;
import com.cr.crandroid.R;
import com.cr.crandroid.base.BaseFragment2;
import com.cr.crandroid.bean.Car;
import com.cr.crandroid.ui.person.user.LoginViewModel;
import com.cr.crandroid.utils.CommonConstant;
import com.cr.crandroid.utils.GlideEngine;
import com.cr.crandroid.utils.OConvertUtils;
import com.cr.crandroid.utils.OkHttpManager;
import com.google.android.material.snackbar.Snackbar;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class AddCarFragment extends BaseFragment2 {
    private Button button;                     // 确认按钮
    private Button button2;                    // 取消按钮
    private ImageButton imageButton;
    private GridLayout gridLayout;

//    private List<ImageView> imageViews;
    private ImageView imageView;
    private EditText editText;
    private EditText editText2;
    private EditText editText3;
    private EditText editText4;
    private EditText editText5;
    private EditText editText6;
    private String url = CommonConstant.URL + "/car/add";
    private String image_upload_url = CommonConstant.URL + "/upload/uploadCarImage";
    private Car car = new Car();
    private static final int REQUEST_CODE_CHOOSE = 23;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 完成视图组件联系
        View root = inflater.inflate(R.layout.fragment_add_car, container, false);
        button = root.findViewById(R.id.button);
        button2 = root.findViewById(R.id.button2);
        button2.setBackgroundColor(Color.RED);
        editText = root.findViewById(R.id.editText);
        editText2 = root.findViewById(R.id.editText2);
        editText3 = root.findViewById(R.id.editText3);
        editText4 = root.findViewById(R.id.editText4);
        editText5 = root.findViewById(R.id.editText5);
        editText6 = root.findViewById(R.id.editText6);
        gridLayout = root.findViewById(R.id.gridLayout);
        imageButton = root.findViewById(R.id.imageButton);
        imageView = root.findViewById(R.id.imageView);
        imageView.setVisibility(View.GONE);

        // 判断是否有参数，有的话就是 “修改”，否则为 “添加”
        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey("car")) {
            String carJson = arguments.getString("car");
            car = new Gson().fromJson(carJson, new TypeToken<Car>() {
            }.getType());
            setComponentsValue(car);
        }

        if (car.getImage() != null) {
            // 设置为可见状态
            imageView.setVisibility(View.VISIBLE);
            // 使用Glide库来加载一张图片
            Glide.with(getContext()).load(car.getImage()).into(imageView);
        }

        // 取消，返回上一个页面
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Navigation.findNavController(view).popBackStack();
            }
        });

        // 添加或修改
        button.setOnClickListener(this::addCar);

        // 点击监听器，例如选择一张图片的操作
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 创建一个相册选择器实例
                EasyPhotos.createAlbum(getActivity(), true, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快）
                        .setFileProviderAuthority("com.cr.crandroid.fileprovider")
                        .setCount(1)        // 图片最多数量为1
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                // 删除已选择的图片，重新添加
                                gridLayout.removeAllViews();
                                gridLayout.addView(imageView);
                                gridLayout.addView(imageButton);
                                String imagePath = "";
                                // 设置图片为可见状态，并加载已选中的图片
                                imageView.setVisibility(View.VISIBLE);
                                GlideEngine.getInstance().loadPhoto(getContext(), photos.get(0).uri, imageView);

                                // 上传图片到服务器，传参为一个MultipartFile文件
                                byte[] imgBytes = photoToBytes(photos.get(0));
                                // 上传图片方法
                                uploadPhotoToServer(imgBytes);
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            }
        });
        return root;
    }

    private void uploadPhotoToServer(byte[] photoBytes) {
        OkHttpClient client = new OkHttpClient();

        // 避免文件名冲突，使用随机数
        String fileName = UUID.randomUUID().toString();

        // 创建RequestBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName+".jpg", RequestBody.create(MediaType.parse("image/jpeg"), photoBytes))
                .build();

        // 创建Request
        Request request = new Request.Builder()
                .url(image_upload_url)
                .post(requestBody)
                .build();

        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 处理结果
                String responseBody = response.body().string();
                JsonParser parser = new JsonParser();
                JsonObject jsonObject = parser.parse(responseBody).getAsJsonObject();
                String success = jsonObject.getAsJsonObject().get("success").toString();
                String message = jsonObject.getAsJsonObject().get("message").toString();
                if(success.equals("true")){
                    JsonObject result = jsonObject.getAsJsonObject("result");
                    // 获取图片路径、品牌、颜色
                    String imageUrl = result.get("url").getAsString();
                    String brand = result.get("brand").getAsString();
                    String color = result.get("color").getAsString();
                    String seatingCapacity = result.get("seatingCapacity").getAsString();
                    String price = result.get("price").getAsString();
                    String year = result.get("year").getAsString();
                    String detail = result.get("detail").getAsString();

                    //  确保在主线程中更新 UI
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            car.setImage(imageUrl); // 假设这是一个方法，用于设置 ImageView 的 URL 或加载图片
                            editText.setText(brand);
                            editText2.setText(color);
                            editText3.setText(seatingCapacity);
                            editText4.setText(price);
                            editText5.setText(year);
                            editText6.setText(detail);
                        }
                    });
                    Snackbar.make(getView(), "车辆属性加载成功", Snackbar.LENGTH_LONG).show();
                }else{
                    Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }

    // Photo 转换为 byte数组
    private byte[] photoToBytes(Photo photo) {
        try {
            InputStream inputStream = requireContext().getContentResolver().openInputStream(photo.uri);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            return stream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 当前为修改页面
    private void setComponentsValue(Car car) {
        button.setText("修改");
        editText.setText(car.getBrand());
        editText2.setText(car.getColor());
        editText3.setText(car.getSeatingCapacity());
        editText4.setText(car.getPrice());
        editText5.setText(car.getYear());
        editText6.setText(car.getDetail());
        url = CommonConstant.URL + "/car/edit";
    }

    // 添加或修改车辆
    private void addCar(View view) {
        String band = editText.getText().toString();
        String color = editText2.getText().toString();
        String seatingCapacity = editText3.getText().toString();
        String price = editText4.getText().toString();
        String year = editText5.getText().toString();
        String detail = editText6.getText().toString();
        if (TextUtils.isEmpty(band)) {
            editText.setError("车辆品牌不能为空");
            return;
        }
        if (TextUtils.isEmpty(color)) {
            editText2.setError("车辆颜色不能为空");
            return;
        }
        if (TextUtils.isEmpty(seatingCapacity)) {
            editText3.setError("车辆座位数不能为空");
            return;
        }
        if (TextUtils.isEmpty(price)) {
            editText4.setError("车辆价格不能为空");
            return;
        }
        if (TextUtils.isEmpty(year)) {
            editText5.setError("车辆年份不能为空");
            return;
        }
        if (TextUtils.isEmpty(detail)) {
            editText6.setError("车辆详情不能为空");
            return;
        }
        car.setBrand(band);
        car.setColor(color);
        car.setSeatingCapacity(seatingCapacity);
        car.setPrice(price);
        car.setYear(year);
        car.setDetail(detail);
        car.setUserId(OConvertUtils.getString(LoginViewModel.user.get("id").toString()));
        car.setStatus(CommonConstant.APPROVE_STATUS_0);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpManager.postJ(url, new Gson().toJson(car), new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String res = response.body().string();
                        JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Snackbar.make(view, "操作成功",
                                        Snackbar.LENGTH_LONG).show();
                                Navigation.findNavController(view).popBackStack();

                            }
                        });
                    }

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }
                });
            }
        }).start();
    }
}